package com.yanqu.timer;

import com.yanqu.CollectServer;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class GeneralTimerMgr {

    private static final Logger log = LogManager.getLogger(GeneralTimerMgr.class.getName());

    private static ScheduledExecutorService timerExecutorService;

    private static SaveDataTask saveDataTask;

    private static CheckBenchmarkTask benchmarkTask;

    private static RemoveUserDataTask removeUserDataTask;

    public static synchronized boolean initGlobalTimers() {
        timerExecutorService = CollectServer.getTimerScheduledExecutorService();
        int interval;
        // 检查玩家心跳
        interval = 600;
        if (null == saveDataTask) {
            saveDataTask = new SaveDataTask();
            timerExecutorService.scheduleWithFixedDelay(saveDataTask, interval, interval, TimeUnit.SECONDS);
        }

        interval = 50;
        if (null == benchmarkTask) {
            benchmarkTask = new CheckBenchmarkTask();
            timerExecutorService.scheduleWithFixedDelay(benchmarkTask, 2, interval, TimeUnit.SECONDS);
        }

        if (null == removeUserDataTask){
            removeUserDataTask = new RemoveUserDataTask();
            timerExecutorService.scheduleWithFixedDelay(removeUserDataTask, 30, 30, TimeUnit.SECONDS);
        }

        return true;
    }


    public static void stop() {
        cancelTask(saveDataTask);
        cancelTask(benchmarkTask);
        cancelTask(removeUserDataTask);
    }

    private static void cancelTask(GeneralTask task) {
        if (null != task) {
            task.cancel(false);
        }
    }
}
